package com.etc.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.etc.dao.AccountMapper;
import com.etc.entity.Account;
import com.etc.service.AccountService;

@Service
public class AccountServiceImpl implements AccountService {

	@Autowired
	private AccountMapper mapper;

	/**
	 * 模拟转账的转入和转出
	 */
	
	@Transactional
	@Override
	public void trans1() {

		// 给账号id为1的人转入5
		mapper.transin(1, 5.0);

		// sleep
		try {
			Thread.sleep(20000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		// 给账号id为2的人转出5
		mapper.transout(2, 5.0);
	}
	
	/**
	 * 可以读取其他事务尚未提交的数据;会产生脏读. isolation = Isolation.READ_UNCOMMITTED
	 */
	//@Transactional(isolation = Isolation.READ_UNCOMMITTED)
	
	@Transactional(isolation = Isolation.READ_COMMITTED)
	@Override
	public Account getById(int accountid) {
		// TODO Auto-generated method stub
		return mapper.getById(accountid);
	}

	/**
	 * 事务的传播特性
	 */
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void trans2(int flag) {
		// 给账号id为1的人转入5
		mapper.transin(1, 5.0);

		if (flag == 2) {
			throw new RuntimeException("ex-trans2");
		}

		// 调用trans3
		trans3(3);

	}

	@Override
	public void trans3(int flag) {

		// 给账号id为2的人转出5
		mapper.transout(2, 5.0);

		// 如果传递一个3
		if (flag == 3) {
			throw new RuntimeException("ex-trans3");
		}

	}

}
